﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CharacterBase : MonoBehaviour

{
    public float health;
    public float maxHealth = 10;
    public int vampireCount;
    public int Count2blood;
    public float noHurtTime = 1;
    public bool IsVampire = false;

    private float tempHealth;
    private float blinkTimer;
    private SpriteRenderer playerrender;
    private bool IsHurt;


    private void Start()
    {
        vampireCount = 0;
        Count2blood = 30;
        tempHealth = health;
        playerrender = GameObject.Find("Player").GetComponent<SpriteRenderer>();
        IsHurt = false;
        health = maxHealth;
    }

    private void Update()
    {
        HealthController();

    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if(collision.gameObject.tag == "Monster")
        {
            health--;
        }
    }//触碰到tag为Monster的怪物掉血

    /// <summary>
    /// 受伤时血量控制，包括音效、受伤期间闪烁且不受二次伤害
    /// </summary>
    private void HealthController()
    {
        if (IsVampire && vampireCount > Count2blood)
        {
            health++;
            vampireCount = 0;
        }

        if (health > maxHealth)
        {
            health = maxHealth;
        }

        if (tempHealth > health && !IsHurt)
        {
            AudioController.Play("playerhurt");
            IsHurt = true;
        }
        else if (tempHealth > health && IsHurt)
        {
            health = tempHealth;
        }
        else if (tempHealth < health)
        {
            AudioController.Play("playerrecover");
        }
        tempHealth = health;

        if (IsHurt)
        {
            Blank();
        }
    }

    /// <summary>
    /// 受伤闪烁
    /// </summary>
    private void Blank()
    {
        blinkTimer += Time.deltaTime;
        if (blinkTimer % 0.2 > 0.1f)
        {
            playerrender.enabled = false;
        }
        else
        {
            playerrender.enabled = true;
        }
        if (blinkTimer > 2)
        {
            blinkTimer = 0;
            IsHurt = false;
        }
    }
}
